<template>
  <div class="dataViewing">
    <el-card shadow="hover" class="layout-padding-auto">
      <el-row>
        <el-col :span="12">
          <div class="header">
            <div class="back" @click="goBack">←返回</div>
            <div class="buttons">
              <el-button type="primary" @click="save()"> 保存 </el-button>
            </div>
          </div>
          <div>提示：勾选多个模块，统一设置查看权限，未勾选模块可单独设置</div>
          <div class="table-container">
            <el-table
              class="mytable"
              :data="dataList.tableData"
              v-bind="$attrs"
              row-key="id"
              stripe
              style="width: 100%"
              v-loading="false"
              :header-cell-style="{
                background: '#E0E0E0',
                color: '#2B2B2B',
                fontWeight: 500
              }"
              @selection-change="selectionChange"
            >
              <el-table-column
                type="selection"
                :reserve-selection="true"
                width="30"
                v-if="true"
              />
              <el-table-column
                type="index"
                label="序号"
                width="66"
                v-if="true"
              />

              <el-table-column
                show-overflow-tooltip
                :width="200"
                label="查看模块"
              >
                <template #default="scope">
                  <div>
                    {{ scope.row.moduleName }}
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="查看权限">
                <template #default="scope">
                  <el-radio-group
                    v-model="scope.row.lookAuthority"
                    @change="
                      groupChange(scope.row.lookAuthority, scope.row.moduleId)
                    "
                  >
                    <el-radio :label="1">仅看个人</el-radio>
                    <el-radio :label="3">公司全部数据</el-radio>

                    <el-radio
                      :label="2"
                      @click="divisionData($event, scope.row)"
                      v-if="
                        scope.row.moduleName != '维保任务列表' &&
                        scope.row.moduleName != '点检任务列表'
                      "
                      >部门数据</el-radio
                    >
                  </el-radio-group>
                </template>
              </el-table-column>

              <template #empty>
                <el-empty description="暂无数据" />
              </template>
            </el-table>
          </div>
        </el-col>
      </el-row>
      <DepartmentDialog
        :dialogVisible="dialogVisible"
        :dialogForm="dialogForm"
        :dialogDetail="dialogDetail"
        @cancel="cancel"
        @submit="submit"
      >
      </DepartmentDialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, defineAsyncComponent } from 'vue'
import { ElAlert, ElMessage } from 'element-plus'
import {
  getModuleList,
  getModuleRight,
  setModuleRight
} from '/@/api/setting/index'
import routes from '/@/router'
import { useRoute } from 'vue-router'
import { number } from '@intlify/core-base'

const route = useRoute()
const roleId = ref(route.query.form).value
const roleName = ref(route.query.name).value
const DepartmentDialog = defineAsyncComponent(
  () => import('./components/DepartmentDialog.vue')
)

const dialogVisible = ref<boolean>(false) //弹窗是否出现
const dialogForm = {
  width: '35%',
  title: '部门权限',
  deptIds: ''
}
const dialogDetail = ref<any>({})

interface User {
  date: string
  name: string
  address: string
}

const dataList = reactive({
  data: [
    { key: 'moduleName', colWidth: '', title: '查看模块', type: 'text' },
    { key: 'lookAuthority', colWidth: '', title: '查看权限', type: 'slot' }
  ],
  tableData: []
})

// 页面加载时
onMounted(() => {
  getListData()
  if (roleName == '超级管理员' || roleName == '试用角色') {
  }
})

const getListData = () => {
  getModuleList(3).then((res1) => {
    if (res1.code == 0) {
      getModuleRight(roleId).then((res2) => {
        if (res2.code == 0) {
          dataList.tableData = res1.data
          for (const item1 of res1.data) {
            for (const item2 of res2.data) {
              if (item1.id == item2.moduleId) {
                item1.moduleId = item2.moduleId
                item1.lookAuthority = item2.lookAuthority
                item1.deptIds = item2.deptIds
              }
            }
          }
        }
      })
    }
  })
}

//返回按钮
const goBack = () => {
  routes.go(-1)
}

//保存按钮
const save = () => {
  let params: any = []
  dataList.tableData.forEach((element: any) => {
    let p = {
      moduleId: String,
      lookAuthority: number,
      deptIds: String
    }
    p.moduleId = element.id
    p.lookAuthority = element.lookAuthority
    p.deptIds = element.deptIds
    params.push(p)
  })
  console.log('params', params)
  // params = params.concat(treeRefPc.value!.getCheckedKeys(false), treeRefSmall.value!.getCheckedKeys(false))
  setModuleRight(roleId, params).then((res) => {
    if (res.code == 0) {
      // routes.push({
      //   name: 'settingRole',
      // })
      ElMessage({
        type: 'success',
        message: '保存成功'
      })
      routes.go(-1)
    }
  })
}

//查看部门数据
const divisionData = (e: any, row: any) => {
  if (e.target.tagName === 'INPUT') return
  dialogDetail.value = row
  dialogVisible.value = !dialogVisible.value
}

// //查看部门数据
// const divisionData = (e: any, row: any) => {
//   console.log('点击事件1', e.target.tagName)
//   if (e.target.tagName === 'INPUT') return;
//   console.log('点击事件2', e.target.tagName)
//   dialogDetail.value = row
//   dialogVisible.value = false
//   dialogVisible.value = true
// }

//(部门权限)弹框取消保存按钮
const cancel = () => {
  getListData()
  dialogVisible.value = !dialogVisible.value
}
const submit = (deptIds: string) => {
  dialogVisible.value = !dialogVisible.value
  dataList.tableData.forEach((element: any) => {
    if (
      selectionList.value.length > 0 &&
      selectionIdList.value.indexOf(dialogDetail.value.id) != -1
    ) {
      selectionList.value.forEach((item: any) => {
        if (item.id == element.id) {
          if (
            element.moduleName == '维保任务列表' ||
            element.moduleName == '点检任务列表'
          ) {
            element.deptIds = deptIds
            return
          }
          element.deptIds = deptIds
          element.lookAuthority = 2
        }
      })
    } else {
      if (element?.id == dialogDetail.value?.id) {
        element.deptIds = deptIds
      }
    }
  })
}

const selectionList = ref<any>([])
const selectionIdList = ref<any>([])

const selectionChange = (selection: any) => {
  selectionIdList.value = []
  selectionList.value = selection
  selection.forEach((element: any) => {
    selectionIdList.value.push(element.id)
  })
}

const groupChange = (val: any, id: any) => {
  if (selectionIdList.value.indexOf(id) != -1) {
    dataList.tableData.forEach((element: any) => {
      selectionList.value.forEach((item: any) => {
        if (selectionList.value.length > 0) {
          if (item.id == element.id) {
            // 维保任务列表  // 点检任务列表
            if (
              element.moduleName == '维保任务列表' ||
              element.moduleName == '点检任务列表'
            ) {
              if (val == 2) {
                return
              } else {
                element.lookAuthority = val
                element.deptIds = ''
              }
            } else {
              element.lookAuthority = val
              if (val != 2) {
                element.deptIds = ''
              }
            }
          }
        }
      })
    })
  }
}
</script>

<style scoped lang="scss">
.table-container {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  margin-top: 10px;

  .el-table {
    flex: 1;
  }

  .table-footer {
    display: flex;
    justify-content: flex-end;
  }
}

.dataViewing {
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .back {
      cursor: pointer;
      color: rgba(140, 140, 140, 1);
    }
  }
}
</style>
